package com.sbtr.business.trainingmodel.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.business.project.mapper.ProjectMapper;
import com.sbtr.business.trainingmodel.entity.ProjectEstimate;
import com.sbtr.business.trainingmodel.mapper.ProjectEstimateMapper;
import com.sbtr.common.PageDto;
import com.sbtr.constant.ColumnConstant;
import com.sbtr.open.trainingtask.dto.TrainingInfoDto;
import com.sbtr.overview.dto.AllCountDto;
import com.sbtr.overview.dto.ModelTypeCountDto;
import com.sbtr.open.project.dto.ProjectDto;
import com.sbtr.business.project.entity.Project;
import com.sbtr.business.project.service.impl.ProjectServiceImpl;
import com.sbtr.open.trainingmodel.dto.ModelCountDto;
import com.sbtr.open.trainingmodel.dto.TrainingModelDataSearchDto;
import com.sbtr.business.trainingmodel.mapper.TrainingModelDataMapper;
import com.sbtr.util.BeanCopyUtils;
import com.sbtr.util.PageDtoUtils;
import com.sbtr.open.trainingmodel.dto.TrainingModelDataDto;
import com.sbtr.business.trainingmodel.entity.TrainingModelData;
import com.sbtr.business.trainingmodel.service.ITrainingModelDataService;
import com.sbtr.business.trainingserver.service.IPublishServerHttpApi;
import com.sbtr.business.trainingtask.entity.TrainingInfo;
import com.sbtr.business.trainingtask.service.impl.TrainingInfoServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.sbtr.util.MinioUtil;

/**
 * <p>
 * 训练模型表 服务实现类
 * </p>
 *
 * @author yuyh2
 */
@Transactional
@Service
public class TrainingModelDataServiceImpl extends ServiceImpl<TrainingModelDataMapper, TrainingModelData>
        implements ITrainingModelDataService {

    private Logger logger = LoggerFactory.getLogger(TrainingModelDataServiceImpl.class);


    @Autowired
    private TrainingInfoServiceImpl trainingInfoService;

    @Autowired
    private ProjectServiceImpl projectService;
    @Resource
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectEstimateMapper projectEstimateMapper;


//	@Autowired
//	private ClassifyHistoryServiceImpl classifyHistoryService;

//	@Autowired
//	private MinioUtil minioUtil;
//
//	@Autowired
//	private OSSUtil ossUtil;
    /**
     * 模型存放路径
     */
    @Value("${training-task.model-base-dir}")
    private String modelBaseDir;

    @Override
    public PageDto<TrainingModelDataDto> search(TrainingModelDataSearchDto pro) {
        IPage<TrainingModelDataDto> page = new Page<>();
        page.setSize(pro.getPageSize());
        page.setCurrent(pro.getPage());
        QueryWrapper<TrainingModelDataDto> wrapper = new QueryWrapper<>();
//		wrapper.eq(ColumnConstant.IS_AVAILABLE, 1);
        wrapper.ne(ColumnConstant.PROJECT_TYPE, "data_unsupervised");
        if (null != pro.getId()) {
            wrapper.like(ColumnConstant.MODEL_ID, pro.getId());
        }

        if (StringUtils.isNotEmpty(pro.getModelName())) {
            wrapper.like(ColumnConstant.MODEL_NAME, pro.getModelName());
        }

        if (null != pro.getApplicationTypes() && !pro.getApplicationTypes().isEmpty()) {
            wrapper.in(ColumnConstant.APPLICATION_TYPE, pro.getApplicationTypes());
        }

        if (StringUtils.isNotEmpty(pro.getVersion())) {
            wrapper.like(ColumnConstant.VERSION, pro.getVersion());
        }
//		if (!roleService.isAdmin(UserUtils.getFdLoginName())) {
//			wrapper.eq(ColumnConstant.CREATER, UserUtils.getFdLoginName());
//		}
        if (StringUtils.isNotEmpty(pro.getCreater())) {
            wrapper.eq(ColumnConstant.MODEL_CREATER, pro.getCreater());
        }

        if (null != pro.getStatus() && !pro.getStatus().isEmpty()) {
            wrapper.in(ColumnConstant.MODEL_STATUS, pro.getStatus());
        }

        if (null != pro.getModelTypes() && !pro.getModelTypes().isEmpty()) {
            wrapper.in(ColumnConstant.PROJECT_TYPE, pro.getModelTypes());
        }

        if (StringUtils.isNotEmpty(pro.getProjectName())) {
            wrapper.like(ColumnConstant.PROJECT_NAME, pro.getProjectName());
        }

        if (StringUtils.isNotEmpty(pro.getMaterialSetName())) {
            wrapper.like(ColumnConstant.FILE_NAME, pro.getMaterialSetName());
        }

        wrapper.orderByDesc("tm.id");
//		page = page(page, wrapper);
        page = baseMapper.customPage(page, wrapper);
        PageDto<TrainingModelDataDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, TrainingModelDataDto.class);
        return pageDto;
    }

    @Override
    public AllCountDto modelCount(String creater) {
        return baseMapper.modelCount(creater);
    }

    @Override
    public List<ModelTypeCountDto> modelTypeCount(String creater) {
        return baseMapper.modelTypeCount(creater);
    }

//	@RequestMapping(value = "/{id}/view-detail", method = RequestMethod.GET)
//	public DetailDto viewById(@PathVariable("id") Long id){
//		return baseMapper.viewById(id);
//	}

    @Override
    public TrainingModelDataDto findById(Long id) {
        // TODO Auto-generated method stub
        TrainingModelDataDto modelDto = BeanCopyUtils.copyProperties(getById(id), TrainingModelDataDto.class);
        if (null != modelDto && null != modelDto.getTaskId()) {
            TrainingInfo trainingTaskData = trainingInfoService.getById(modelDto.getTaskId());
            modelDto.setType(trainingTaskData.getType());
            // 查询标签信息
//			QueryWrapper<ClassifyHistory> claWrapper = new QueryWrapper<>();
//			claWrapper.eq(ColumnConstant.TASK_ID, modelDto.getTaskId());
//			List<ClassifyHistory> hisList = classifyHistoryService.list(claWrapper);
//			hisList.forEach(his -> his.setId(his.getOldId()));
//			List<ClassifyInfo> infoList = BeanCopyUtils.copyProperties(hisList, ClassifyInfo.class);
//			modelDto.setClassify(JSONObject.toJSONString(infoList));
        }
        return modelDto;
    }

    @Override
    public boolean deleteById(Long id) {
        // TODO Auto-generated method stub
        TrainingModelData model = getById(id);
        // 只有创建者或者管理员有权限删除
        Assert.isTrue((model != null
//						&& model.getCreater().equalsIgnoreCase(UserUtils.getFdLoginName()))
//				|| roleService.isAdmin(UserUtils.getFdLoginName())
        ), "权限不足")
        ;
        // 发布状态不可以删除
        String status = model.getStatus();
        if (TrainingModelDataDto.MODEL_STATUS_PUBLISHED.equals(status)) {
            logger.warn("id为[{}]的模型状态为[{}],不能删除", id, status);
            throw new RuntimeException("模型状态为[" + status + "],不能删除");
        }
        return removeById(id);
    }

    @Override
    public PageDto<TrainingModelDataDto> search(String modelName, Long currPage, Long pageSize, Long projectId) {
        // TODO Auto-generated method stub
        IPage<TrainingModelData> page = new Page<>();
        if (currPage != null) {
            page.setCurrent(currPage);
        }
        if (pageSize != null) {
            page.setSize(pageSize);
        }

        QueryWrapper<TrainingModelData> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(modelName)) {
            wrapper.like("model_name", modelName);
        }
        if (projectId != null) {
            wrapper.eq("project_id", projectId);
        }

        ProjectDto projectDto = projectService.findById(projectId);
        if (projectDto.getCreater() != null) {
            wrapper.eq("creater", projectDto.getCreater());
        }

        wrapper.orderByDesc("create_time");

        page = page(page, wrapper);

        PageDto<TrainingModelDataDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, TrainingModelDataDto.class);
//		this.setTaskType(pageDto.getList());
        this.setProjectName(pageDto.getList());
        return pageDto;
    }

    private void setProjectName(List<TrainingModelDataDto> list) {
        if (list != null && !list.isEmpty()) {
            List<Long> projectIdList = new ArrayList<>();
            list.forEach(m -> projectIdList.add(m.getProjectId()));
            QueryWrapper<Project> pWrapper = new QueryWrapper<>();
            pWrapper.in("id", projectIdList);
            List<Project> projectList = projectService.list(pWrapper);
            if (projectList != null && !projectList.isEmpty()) {
                for (TrainingModelDataDto dto : list) {
                    for (Project project : projectList) {
                        if (dto.getProjectId().equals(project.getId())) {
                            dto.setProjectName(project.getProjectName());
                            break;
                        }
                    }
                }
            }
        }
    }

    private void setTaskType(List<TrainingModelDataDto> list) {
        if (list != null && !list.isEmpty()) {
            List<Long> taskIdList = new ArrayList<>();
            for (TrainingModelDataDto modelDto : list) {
                if (modelDto.getTaskId() != null && !taskIdList.contains(modelDto.getTaskId())) {
                    taskIdList.add(modelDto.getTaskId());
                }
            }
            // 查询关联的训练任务
            if (taskIdList != null && !taskIdList.isEmpty()) {
                QueryWrapper<TrainingInfo> taskWrapper = new QueryWrapper<>();
                taskWrapper.in("id", taskIdList);
                List<TrainingInfo> taskList = trainingInfoService.list(taskWrapper);
                // 设置训练任务的类型
                if (taskList != null && !taskList.isEmpty()) {
                    for (TrainingModelDataDto modelDto : list) {
                        for (TrainingInfo trainingTask : taskList) {
                            if (modelDto.getTaskId().equals(trainingTask.getId())) {
                                modelDto.setType(trainingTask.getType());
                                break;
                            }
                        }
                    }
                } //

            }
        }
    }

    @Override
    public boolean publish(Long id) {
        // TODO Auto-generated method stub
        TrainingModelData model = getById(id);
        if (model != null) {
            model.setStatus(TrainingModelDataDto.MODEL_STATUS_PUBLISHED);
        }
        return false;
    }

    @Override
    public TrainingModelDataDto save(TrainingModelDataDto dto) {
        // TODO Auto-generated method stub
        TrainingModelData trainingModel = BeanCopyUtils.copyProperties(dto, TrainingModelData.class);
        saveOrUpdate(trainingModel);
        dto.setId(trainingModel.getId());
        return dto;
    }

	/*
	private String getDataSdk(Long id) throws IOException {

		TrainingModelDataDto modelDto = this.findById(id);
		Assert.notNull(modelDto, "模型不存在");
		if (StringUtils.isNotBlank(modelDto.getSdkModelDir())) {
			String url = ossUtil.getObjectUrl(modelDto.getSdkModelDir());
			if (StringUtils.isNotBlank(url)) {
				return url;
			} else {
				throw new BizException("oss获取sdk出错了");
			}
		}

		TrainingInfoDto trainingTaskDto = trainingInfoService.findById(modelDto.getTaskId());
		Assert.notNull(trainingTaskDto, "训练任务不存在");
//		String sdkName = publishServerHttpApi.getDataSdk(trainingTaskDto, modelDto);
//		modelDto.setSdkModelDir(sdkName);
		this.save(modelDto);
		String url = ossUtil.getObjectUrl(modelDto.getSdkModelDir());
		if (StringUtils.isNotBlank(url)) {
			return url;
		} else {
			throw new BizException("oss获取sdk出错了");
		}
	}
*/

//	/**
//	 * 模型文件打包配置生成SDK
//	 *
//	 * @param id
//	 * @return
//	 * @throws IOException
//	 */
//	private String getSdk(Long id) throws IOException {
//
//		TrainingModelDataDto modelDto = this.findById(id);
//		Assert.notNull(modelDto, "模型不存在");
//		if (StringUtils.isNotBlank(modelDto.getModelDir())) {
//
//			String modelDir=modelDto.getModelDir();
//			String bucketName=modelDir.substring(0,modelDir.indexOf("/"));
//			String objectName=modelDir.substring(modelDir.indexOf("/")+1,modelDir.length());
//			String url="";
//			try {
//				url= minioUtil.getObjectUrl(bucketName, objectName);
//			}
//			catch (Exception e){
//				e.printStackTrace();
//			}
//			if (StringUtils.isNotBlank(url)) {
//				return url;
//			} else {
//				throw new BizException("oss获取sdk出错了");
//			}
//
//		}
//		return "获取模型地址失败";
//	}


    /**
     * 模型文件打包配置生成SDK
     *
     * @param id
     * @return
     * @throws IOException
     */
    private String getSdk(Long id) {

        TrainingModelDataDto modelDto = this.findById(id);
        Assert.notNull(modelDto, "模型不存在");
        InputStream in;
        if (StringUtils.isNotBlank(modelDto.getModelDir())) {
            String modelDir = modelDto.getModelDir();
            return modelDir;
        } else {
            return "找不到地址";
        }
    }


//	/**
//	 * 模型文件打包配置生成SDK
//	 *
//	 * @param id
//	 * @return
//	 * @throws IOException
//	 */
//	private String  getSdk(Long id) throws IOException {
//
//		TrainingModelDataDto modelDto = this.findById(id);
//		Assert.notNull(modelDto, "模型不存在");
//		if (StringUtils.isNotBlank(modelDto.getModelDir())) {
//
//			String modelDir=modelDto.getModelDir();
//			String bucketName=modelDir.substring(0,modelDir.indexOf("/"));
//			String objectName=modelDir.substring(modelDir.indexOf("/")+1,modelDir.length());
//			String url="";
//			try {
//				url= minioUtil.getObjectUrl(bucketName, objectName);
//			}
//			catch (Exception e){
//				e.printStackTrace();
//			}
//			if (StringUtils.isNotBlank(url)) {
//				return url;
//			} else {
//				throw new BizException("oss获取sdk出错了");
//			}
//
//		}
//		return "获取模型地址失败";
//	}


//	@Override
//	@RequestMapping(value = "/model-data-sdk/{id}", method = RequestMethod.GET)
//	public String modelDataSDK(@PathVariable("id") Long id) throws IOException {
//		TrainingModelDataDto modelDto = this.findById(id);
//		Assert.notNull(modelDto, "模型不存在");
//
////		TrainingTaskData trainingTaskData = trainingTaskDataService.getById(modelDto.getTaskId());
//		TrainingInfo trainingTaskData = trainInfo.getById(modelDto.getTaskId());
//
//		Assert.notNull(trainingTaskData, "训练任务不存在");
//		return this.getSdk(id);
//	}


    @Override
    public String modelDataSDK(Long id) {
        TrainingModelDataDto modelDto = this.findById(id);
        Assert.notNull(modelDto, "模型不存在");

//		TrainingTaskData trainingTaskData = trainingTaskDataService.getById(modelDto.getTaskId());
//		TrainingInfo trainingTaskData = trainInfo.getById(modelDto.getTaskId());

//		Assert.notNull(trainingTaskData, "训练任务不存在");

        String modelDir = getSdk(id);
        return modelDir;
//		return this.getSdk(id);
    }


    @Override
    public TrainingModelDataDto findByTrainingTask(Long taskId) {
        QueryWrapper<TrainingModelData> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", taskId);
        wrapper.orderByDesc("create_time");
        List<TrainingModelData> list = this.list(wrapper);

        //多个算法执行情况
        List<TrainingModelData> list2 = new ArrayList<>();

//        String projectType = "data_predict";//默认
        String type= "1001";
        if (list != null && !list.isEmpty()) {
            //查询结果数据
            QueryWrapper<TrainingModelData> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("project_id", list.get(0).getProjectId());
            wrapper2.orderByDesc("create_time");
            list2 = this.list(wrapper2);
            //查询算法类型
            TrainingInfoDto trainingInfoDto=trainingInfoService.getByProjectId(list.get(0).getProjectId());
            type=trainingInfoDto.getType();

//            //项目类型
//            Project project = projectMapper.selectById(list.get(0).getProjectId());
//            projectType=project.getProjectType();
        }

        if (list2 != null && !list2.isEmpty()) {
            TrainingModelDataDto trainingModelDataDto;
//            if (list2.size() > 1) {
                trainingModelDataDto=BeanCopyUtils.copyProperties(compareBest(type,list2), TrainingModelDataDto.class);
//            }else{
//                trainingModelDataDto=BeanCopyUtils.copyProperties(list2.get(0), TrainingModelDataDto.class);
//            }
//            String evaluate = trainingModelDataDto.getEvaluate();
//            JSONObject jsonObject = JSONUtil.parseObj(evaluate);
//            JSONObject testObj = JSONUtil.parseObj(jsonObject.get("test"));
//            JSONObject trainObj = JSONUtil.parseObj(jsonObject.get("train"));
//            for (Object o:testObj.values()) {
//                double data = Double.parseDouble(o.toString());
//                if(data<=0.1){
//                    throw new RuntimeException("准确率过低");
//                }
//            }
//            for (Object o:trainObj.values()) {
//                double data = Double.parseDouble(o.toString());
//                if(data<=0.1){
//                    throw new RuntimeException("准确率过低");
//                }
//            }
            return trainingModelDataDto;
        }
        return null;
    }

    //预估比较
    public TrainingModelData compareBest(String type,List<TrainingModelData> list) {

        if(CollectionUtil.isEmpty(list)){
            throw new RuntimeException("不存在训练数据");
        }
        String projectId = list.get(0).getProjectId().toString();
        QueryWrapper<ProjectEstimate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id",projectId);
        List<ProjectEstimate> projectEstimate = projectEstimateMapper.selectList(queryWrapper);

        String dataName="test";
        if(CollectionUtil.isNotEmpty(projectEstimate)){
            JSONArray array = JSONUtil.parseArray(projectEstimate.get(0).getConfigSet());
            return sortCompare(list,dataName,array);
        }else{
            JSONArray array = new JSONArray();
            JSONObject o1= new JSONObject();
            JSONObject o2= new JSONObject();
            JSONObject o3= new JSONObject();
            JSONObject o4= new JSONObject();
            switch (type){//根据排序判断,[{a:1},{b,0}]
                case "1001"://分类
                    o1.set("accuracy",1);//准确率
                    o2.set("fl_score",1);//F1值
                    o3.set("recall",1);//召回率
                    array.add(o1);
                    array.add(o2);
                    array.add(o3);
                    return sortCompare(list,dataName,array);
                case "1002"://回归
                    o1.set("rmse",0);//均方根误差
                    o2.set("r2_score",1);//拟合优度
                    o3.set("mape",0);//平均绝对百分误差
                    o4.set("mae",0);//平均绝对误差
                    array.add(o1);
                    array.add(o2);
                    array.add(o3);
                    array.add(o4);
                    return sortCompare(list,dataName,array);
            }
        }

        return list.get(0);
    }

    //迭代比较
    private TrainingModelData sortCompare(List<TrainingModelData> list,String data,JSONArray params){
        TrainingModelData best = null;
        JSONObject bestTest = null;
        line:
        for (TrainingModelData trainingModelData : list) {
            String evaluate = trainingModelData.getEvaluate();
            JSONObject jsonObject = JSONUtil.parseObj(evaluate);
            if (best == null) {//存储第一条
                best = trainingModelData;
                if (jsonObject.get(data) != null) {
                    bestTest = JSONUtil.parseObj(jsonObject.get(data));
                }
                continue;
            }
            try {//防止不存在数据报错
                if (jsonObject.get(data) != null) {
                    JSONObject testObj = JSONUtil.parseObj(jsonObject.get(data));
                    assert bestTest != null;

                    for (Object o:params) {//多条，[{a:1},{b,0}]
                        JSONObject json = (JSONObject)o;
                        for (Map.Entry<String,Object> entry:json.getRaw().entrySet()) {//只有一条
                            double oldData = Double.parseDouble(bestTest.get(entry.getKey()).toString());
                            double newData = Double.parseDouble(testObj.get(entry.getKey()).toString());
                            if(entry.getValue().toString().equals("1")){//1为越好大越好，0为越小越好
                                if (oldData < newData) {
                                    bestTest = testObj;
                                    best = trainingModelData;
                                    continue line;
                                } else if (oldData > newData) {
                                    continue line;
                                }
                            }else{
                                if (oldData > newData) {
                                    bestTest = testObj;
                                    best = trainingModelData;
                                    continue line;
                                } else if (oldData < newData) {
                                    continue line;
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return best;
    }

    //迭代比较
    private TrainingModelData sortCompare2(List<TrainingModelData> list,String data,LinkedHashMap<String,Boolean> params){
        TrainingModelData best = null;
        JSONObject bestTest = null;
        line:
        for (TrainingModelData trainingModelData : list) {
            String evaluate = trainingModelData.getEvaluate();
            JSONObject jsonObject = JSONUtil.parseObj(evaluate);
            if (best == null) {//存储第一条
                best = trainingModelData;
                if (jsonObject.get(data) != null) {
                    bestTest = JSONUtil.parseObj(jsonObject.get(data));
                }
                continue;
            }
            try {//防止不存在数据报错
                if (jsonObject.get(data) != null) {
                    JSONObject testObj = JSONUtil.parseObj(jsonObject.get(data));
                    assert bestTest != null;

                    for (Map.Entry<String,Boolean> entry:params.entrySet()) {
                        double oldData = Double.parseDouble(bestTest.get(entry.getKey()).toString());
                        double newData = Double.parseDouble(testObj.get(entry.getKey()).toString());
                        if(entry.getValue()){//TRUE为越好大越好，FALSE为越小越好
                            if (oldData < newData) {
                                bestTest = testObj;
                                best = trainingModelData;
                                continue line;
                            } else if (oldData > newData) {
                                continue line;
                            }
                        }else{
                            if (oldData > newData) {
                                bestTest = testObj;
                                best = trainingModelData;
                                continue line;
                            } else if (oldData < newData) {
                                continue line;
                            }
                        }

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return best;
    }

    @Override
    public TrainingModelDataDto findPublishByProject(Long projectId) {
        // TODO Auto-generated method stub
        QueryWrapper<TrainingModelData> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        wrapper.eq("status", TrainingModelDataDto.MODEL_STATUS_PUBLISHED);
        wrapper.orderByDesc("create_time");
        List<TrainingModelData> list = this.list(wrapper);

        //多个算法执行情况
        List<TrainingModelData> list2 = new ArrayList<>();
        String type= "1001";
        if (list != null && !list.isEmpty()) {
            //查询结果数据
            QueryWrapper<TrainingModelData> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("project_id", list.get(0).getProjectId());
            wrapper2.orderByDesc("create_time");
            list2 = this.list(wrapper2);
            //查询算法类型
            TrainingInfoDto trainingInfoDto=trainingInfoService.getByProjectId(list.get(0).getProjectId());
            type=trainingInfoDto.getType();
        }

        if (list2 != null && !list2.isEmpty()) {
//            if (list2.size() > 1) {
                return BeanCopyUtils.copyProperties(compareBest(type,list), TrainingModelDataDto.class);
//            }
//            return BeanCopyUtils.copyProperties(list2.get(0), TrainingModelDataDto.class);
        }
        return null;
    }


    @Override
    public TrainingModelDataDto findByProjectId(Long projectId) {
//        QueryWrapper<TrainingInfo> trainingInfoQueryWrapper = new QueryWrapper<>();
//        trainingInfoQueryWrapper.eq("project_id", projectId);
//        trainingInfoQueryWrapper.orderByDesc("create_time");
//        List<TrainingInfo> trainingInfos = trainingInfoService.list(trainingInfoQueryWrapper);

//        String type = trainingInfos.get(0).getType();
        // TODO Auto-generated method stub
        QueryWrapper<TrainingModelData> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        wrapper.orderByDesc("create_time");
        List<TrainingModelData> list = this.list(wrapper);
        //多个算法执行情况
        List<TrainingModelData> list2 = new ArrayList<>();
        String type= "1001";
        if (list != null && !list.isEmpty()) {
            //查询结果数据
            QueryWrapper<TrainingModelData> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("project_id", list.get(0).getProjectId());
            wrapper2.orderByDesc("create_time");
            list2 = this.list(wrapper2);
            //查询算法类型
            TrainingInfoDto trainingInfoDto=trainingInfoService.getByProjectId(list.get(0).getProjectId());
            type=trainingInfoDto.getType();
        }

        if (list2 != null && !list2.isEmpty()) {
//            if (list2.size() > 1) {
                return BeanCopyUtils.copyProperties(compareBest(type,list), TrainingModelDataDto.class);
//            }
//            TrainingModelDataDto trainingModelDataDto = BeanCopyUtils.copyProperties(list2.get(0), TrainingModelDataDto.class);
//            trainingModelDataDto.setType(type);
//            return trainingModelDataDto;
        }
        return null;
    }


    @Override
    public TrainingModelDataDto findModelByProject(Long projectId) {
        // TODO Auto-generated method stub
        QueryWrapper<TrainingModelData> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        wrapper.orderByDesc("create_time");
        List<TrainingModelData> list = this.list(wrapper);
        if (list != null && !list.isEmpty()) {
            if (list.size() != 1) {
                logger.warn("当前项目有多个上线的模型");
            }
            return BeanCopyUtils.copyProperties(list.get(0), TrainingModelDataDto.class);
        }
        return null;
    }

    @Override
    public List<ModelCountDto> modelCountByProject(List<Long> projectIds) {
        // TODO Auto-generated method stub
        return baseMapper.modelCountByProject(projectIds);
    }

//	@Override
//	@RequestMapping(value = "/get-history-model-by-project/{projectId}", method = RequestMethod.POST)
//	public List<HistoryModelDto> findHistoryModelByProjectId(Long projectId, Long currPage, Long pageSize) {
//		// TODO Auto-generated method stub
//		IPage<TrainingModelData> page = new Page<>();
//		if (currPage != null) {
//			page.setCurrent(currPage);
//		}
//		if (pageSize != null) {
//			page.setSize(pageSize);
//		}
//
//		QueryWrapper<TrainingModelData> wrapper = new QueryWrapper<>();
//		if (projectId != null) {
//			wrapper.eq("project_id", projectId);
//		}
//
//		wrapper.eq("creater", UserUtils.getFdLoginName());
//		wrapper.orderByDesc("create_time");
//
//		page = page(page, wrapper);
//
//		PageDto<TrainingModelDataDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, TrainingModelDataDto.class);
//		List<TrainingModelDataDto> trainingModelList = pageDto.getList();
//		List<HistoryModelDto> modeResultList = new ArrayList<>();
//		for (TrainingModelDataDto dto : trainingModelList) {
//			Long taskId = dto.getTaskId();
//			TrainingTaskDataDto trainingTaskDto = trainingTaskDataService.findById(taskId);
//			String arithmetic = trainingTaskDto.getArithmetic();
//			String classifier = dto.getClassifier();
//			HistoryModelDto historyModelDto = BeanCopyUtils.copyProperties(dto, HistoryModelDto.class);
//			historyModelDto.setModelId(dto.getId());
//			historyModelDto.setArithmetic(arithmetic);
//			String evaluateStr = dto.getEvaluate();
//			try {
//				JSONObject evaluateJSON = JSONObject.parseObject(evaluateStr);
//				historyModelDto.setEvaluateModel(evaluateJSON);
//			} catch (Exception e) {
//				e.printStackTrace();
//				logger.warn("模型评估指标转换出错了, 返回前端结果张不包含评估结果");
//			}
//
//			try {
//				JSONObject trainDataParams = JSONObject.parseObject(classifier);
//				historyModelDto.setTrianDataParams(trainDataParams);
//			} catch (Exception e) {
//				e.printStackTrace();
//				logger.warn("模型训练数据的相关信息转换出错, 返回前端结果将不包含评估信息");
//			}
//			modeResultList.add(historyModelDto);
//		}
//
//		return modeResultList;
//	}

    @Override
    public List<TrainingModelDataDto> trainMoedlStatus(int howLong) {
        // TODO Auto-generated method stub
        // 获取n天前的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calDate = Calendar.getInstance();
        calDate.set(Calendar.HOUR_OF_DAY, 0);
        calDate.set(Calendar.MINUTE, 0);
        calDate.set(Calendar.SECOND, 0);
        Date time = calDate.getTime();
        if (howLong != 0) {
            calDate.add(Calendar.DAY_OF_YEAR, -howLong);
            time = calDate.getTime();
        } else {
            time = calDate.getTime();
        }
        String timeString = sdf.format(time);

        // 获取n天内的训练模型结果
        List<TrainingModelDataDto> trainModelList = baseMapper.queryByCreateTime(timeString);

        // 获取指定字段的值
        List<TrainingModelDataDto> trainModelStatus = new ArrayList<TrainingModelDataDto>();
        for (TrainingModelDataDto i : trainModelList) {
            // 仅返回已训练完成task
            if (i.getStatus() != null && i.getStatus().equals("unpublish")) {
                trainModelStatus.add(i);
            }
        }
        return trainModelStatus;
    }


}
